<template>
  <div class="payment-container">

    <el-card class="payment-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-button 
              @click="goBackToPendingOrders" 
              class="back-button"
              text
            >
              <el-icon><ArrowLeft /></el-icon>
              返回
            </el-button>
          </div>
          <div class="title-wrapper">
           <div class="title-status-wrapper">
        <h1 class="title">订单支付</h1>
        <el-tag type="success" v-if="paymentStatus === 'paid'">支付成功</el-tag>
        <el-tag type="warning" v-else-if="paymentStatus === 'pending'">待支付</el-tag>
        <el-tag type="danger" v-else-if="paymentStatus === 'failed'">支付失败</el-tag>
      </div>
          </div>
          <div class="order-code">订单编号: {{ orderData.order_code }}</div>
        </div>
      </template>

      <div class="payment-content">
        <el-steps :active="paymentStepsActive" finish-status="success" class="payment-steps">
          <el-step title="提交订单" description="已成功提交订单"></el-step>
          <el-step title="确认支付" description="请完成支付"></el-step>
          <el-step title="完成" description="支付成功"></el-step>
        </el-steps>

        <el-divider></el-divider>

        <div class="payment-details">
          <el-card shadow="never" class="detail-card">
            <div class="detail-item">
              <span class="label">商品名称</span>
              <span class="value">{{ orderData.product_title }}</span>
            </div>
            <div class="detail-item">
              <span class="label">商品价格</span>
              <span class="value">¥{{ orderData.snapshot_price }}</span>
            </div>
            <div class="detail-item">
              <span class="label">运费</span>
              <span class="value">¥0.00</span>
            </div>
            <el-divider></el-divider>
            <div class="detail-item total">
              <span class="label">应付总额</span>
              <span class="value">¥{{ orderData.snapshot_price }}</span>
            </div>
          </el-card>

          <el-card shadow="never" class="payment-methods">
            <template #header>
              <div class="payment-methods-header">
                <h3>选择支付方式</h3>
              </div>
            </template>
            <div class="method-options">
              <el-radio-group v-model="selectedPaymentMethod">
                <el-radio label="wechat" border class="payment-method">
                  <el-icon :size="24" color="#09BB07"><ChatDotRound /></el-icon>
                  <span>微信支付</span>
                </el-radio>
                <el-radio label="alipay" border class="payment-method">
                  <el-icon :size="24" color="#1677FF"><Opportunity /></el-icon>
                  <span>支付宝</span>
                </el-radio>
              </el-radio-group>
            </div>
          </el-card>
        </div>
      </div>

      <div class="submit-area">
        <el-button
          type="primary"
          size="large"
          :loading="isPaying"
          :disabled="isPaying"
          @click="initiatePayment"
          class="pay-button"
        >
          <span v-if="!isPaying">立即支付 ¥{{ orderData.snapshot_price }}</span>
          <span v-else>支付处理中...</span>
        </el-button>
        <p class="payment-tips">
          <el-icon><Warning /></el-icon>
          请在30分钟内完成支付，超时订单将自动取消
        </p>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  ChatDotRound, 
  Opportunity,
  Warning
} from '@element-plus/icons-vue'
import apiClient from '@/utils/request'
import { onBeforeRouteLeave } from 'vue-router'
onBeforeRouteLeave((to, from, next) => {
  // 如果要去的是订单确认页面，直接跳转到个人中心
  if (to.path === '/orders') {
    next('/Mine/maidao')
  } else {
    next()
  }
})
const route = useRoute()
const router = useRouter()
const isPaying = ref(false)
const paymentStatus = ref('pending') // 'pending', 'paid', 'failed'
const paymentStepsActive = ref(1)
const selectedPaymentMethod = ref('wechat')
// 订单数据
const orderData = reactive({
  order_id: '',
  order_code: '',
  product_title: '',
  snapshot_price: ''
})

// 加载订单信息
const loadOrderInfo = async () => {
  try {
    // 从路由参数获取订单信息
    if (route.query.order_code) {
      orderData.order_id = route.query.order_id || ''
      orderData.order_code = route.query.order_code
      orderData.product_title = route.query.product_title || ''
      orderData.snapshot_price = route.query.snapshot_price || '0.00'
      
      // 验证必要字段
      if (!orderData.order_code) {
        throw new Error('订单编号缺失')
      }
      
      return
    }

    // 如果路由参数中没有完整信息，尝试从API获取
    const token = localStorage.getItem('access_token')
    if (!token) {
      router.push('/login')
      return
    }

    if (route.query.order_id) {
      const response = await apiClient.get(`/api/orders/${route.query.order_id}/`, {
        headers: { 'Authorization': `Bearer ${token}`,'Content-Type': 'application/json'}
      })
      
      const order = response.data
      orderData.order_id = order.id
      orderData.order_code = order.order_code
      orderData.snapshot_price = order.snapshot_price
      
      // 如果product_title不存在，尝试获取商品信息
      if (!orderData.product_title && order.product_code) {
        const productResponse = await apiClient.get(`/api/products/buyer/${order.product_code}/`)
        orderData.product_title = productResponse.data.name || order.product_title || '未知商品'
      }
    }
  } catch (error) {
    console.error('加载订单信息失败:', error)
    ElMessage.error(error.message || '加载订单信息失败')
    router.push('/orders/pending')
  }
}

// 发起支付请求
const initiatePayment = async () => {
  try {
    isPaying.value = true

    // 验证订单编号
    if (!orderData.order_code) {
      throw new Error('订单编号缺失，请返回重新选择订单')
    }

    // 调用支付接口
    const response = await apiClient.post(`/api/orders/${orderData.order_code}/pay/`, {
      payment_method: selectedPaymentMethod.value
    },{headers: { 'Content-Type': 'application/json' } })

    if (response.data && response.data.status === 'success') {
      paymentStatus.value = 'paid'
      paymentStepsActive.value = 3
      
      // 跳转到支付成功页
      router.push({
        path: '/paySuccess',
        query: {
          order_code: orderData.order_code,
          product_title: orderData.product_title,
          snapshot_price: orderData.snapshot_price
        }
      })
    } else {
      throw new Error(response.data?.message || '支付失败，请稍后重试')
    }
  } catch (error) {
    console.error('支付失败:', error)
    paymentStatus.value = 'failed'
    showPaymentError(error)
  } finally {
    isPaying.value = false
  }
}

// 支付失败提示
const showPaymentError = (error) => {
  const errorMessage = error.message || '支付失败，请稍后重试'
  
  ElMessageBox.confirm(
    `支付失败: ${errorMessage}`,
    '支付失败',
    {
      confirmButtonText: '重试支付',
      cancelButtonText: '返回订单',
      type: 'error',
      closeOnClickModal: false,
      closeOnPressEscape: false,
      showClose: false
    }
  ).then(() => {
    // 重试前重新加载订单信息
    loadOrderInfo().then(() => {
      if (orderData.order_code) {
        initiatePayment()
      } else {
        ElMessage.error('订单信息加载失败，请返回重新选择订单')
        router.push('/orders/pending')
      }
    })
  }).catch(() => {
    router.push('/orders/pending')
  })
}

// 初始化校验
onMounted(async () => {
  const token = localStorage.getItem('access_token')
  if (!token) {
    ElMessage.error('请先登录')
    router.push('/login')
    return
  }
  try {
    await loadOrderInfo()
    
    // 验证必要字段
    if (!orderData.order_code) {
      throw new Error('订单信息不完整')
    }
    // 验证订单状态是否为待支付
    const orderStatusResponse = await apiClient.get(`/api/orders/${orderData.order_code}/`)
    if (orderStatusResponse.data.status !== 0) { // 0 为待支付状态
      ElMessage.warning('该订单状态已改变')
      router.push('/Mine/maidao')
      return
    }
  } catch (error) {
    ElMessage.error(error.message || '订单信息加载失败')
    router.push('/orders/pending')
  }
})

// 返回待支付订单页面
const goBackToPendingOrders = () => {
  router.push('/Mine/maidao')
}
</script>

<style scoped>
.payment-container {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  min-height: 100vh;
  padding: 20px;
  background-color: #f5f7fa;
}

.payment-card {
  width: 100%;
  max-width: 800px;
  border-radius: 12px;
}

.card-header {
  display: flex;
  align-items: center;
  position: relative;
  padding: 0 20px;
}
.header-left {
  position: absolute;
  left: 0;
}
.title-wrapper {
  flex: 1;
  text-align: center;
}
.title-status-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
}
.title {
  margin: 0;
  color: var(--el-text-color-primary);
  font-size: 24px;
}

.order-code {
  position: absolute;
  right: 20px;
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

.payment-content {
  padding: 0 20px;
}

.payment-steps {
  margin-bottom: 20px;
}

.payment-details {
  display: grid;
  grid-template-columns: 1fr;
  gap: 20px;
  margin-top: 20px;
}

.detail-card, .payment-methods {
  border-radius: 8px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  font-size: 15px;
}

.detail-item.total {
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px dashed var(--el-border-color);
  font-size: 18px;
  font-weight: bold;
}

.label {
  color: var(--el-text-color-secondary);
}

.value {
  color: var(--el-text-color-primary);
}

.payment-methods-header {
  display: flex;
  align-items: center;
}

.payment-methods-header h3 {
  margin: 0;
  font-size: 16px;
  color: var(--el-text-color-primary);
}

.method-options {
  padding: 10px;
}

.payment-method {
  width: 48%;
  height: 60px;
  margin-right: 2%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.payment-method :deep(.el-radio__label) {
  display: flex;
  align-items: center;
  gap: 8px;
}

.submit-area {
  margin-top: 30px;
  text-align: center;
  padding: 0 20px 20px;
}

.pay-button {
  width: 100%;
  height: 50px;
  font-size: 16px;
  font-weight: bold;
}

.payment-tips {
  margin-top: 15px;
  color: var(--el-color-warning);
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

.back-button {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #606266;
}
.back-button:hover {
  color: var(--el-color-primary);
}
</style>